import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { FriendAddDto } from './dto/friend-add.dto';

@Injectable()
export class FriendshipService {
  @Inject(PrismaService)
  private prismaService: PrismaService;

  // 添加好友申请接口
  async add(userId: number, friendAddDto: FriendAddDto) {
    // 判断用户是否存在数据库
    const user = await this.prismaService.user.findUnique({
      where: {
        username: friendAddDto.username,
      },
    });
    if (!user) {
      throw new BadRequestException('用户不存在');
    }

    if (userId === user.id) {
      throw new BadRequestException('不能添加自己为好友');
    }

    // 判断是否已经是好友
    const isFriend = await this.prismaService.friendShip.findFirst({
      where: {
        OR: [
          {
            userId,
            friendId: user.id,
          },
          {
            userId: user.id,
            friendId: userId,
          },
        ],
      },
    });

    if (isFriend) {
      throw new BadRequestException('已经是好友了');
    }

    // 判断是否已经发送过好友申请
    const isPendingRequest = await this.prismaService.friendRequest.findFirst({
      where: {
        fromUserId: userId,
        toUserId: user.id,
        status: 'Pending',
      },
    });

    if (isPendingRequest) {
      throw new BadRequestException('好友申请待处理，请耐心等待!');
    }

    await this.prismaService.friendRequest.create({
      data: {
        fromUserId: userId,
        toUserId: user.id,
        reason: friendAddDto.reason,
      },
    });
  }

  // 获取申请列表接口
  async request_list(userId: number) {
    const res = {
      fromMe: [],
      toMe: [],
    };

    // 我发送的申请
    const fromMeRequests = await this.prismaService.friendRequest.findMany({
      where: {
        fromUserId: userId,
      },
    });

    // 我接收的申请
    const toMeRequests = await this.prismaService.friendRequest.findMany({
      where: {
        toUserId: userId,
      },
    });

    // 查询用户信息
    for (let i = 0; i < fromMeRequests.length; i++) {
      const user = await this.prismaService.user.findUnique({
        where: {
          id: fromMeRequests[i].toUserId,
        },
      });
      res.fromMe.push({
        ...fromMeRequests[i],
        toUser: user,
      });
    }

    // 查询用户信息
    for (let i = 0; i < toMeRequests.length; i++) {
      const user = await this.prismaService.user.findUnique({
        where: {
          id: toMeRequests[i].fromUserId,
        },
      });
      res.toMe.push({
        ...toMeRequests[i],
        fromUser: user,
      });
    }

    return res;
  }

  // 同意申请接口
  async aggree(userId: number, fromId: number) {
    // 更新好友请求状态->已同意, 用 updateMany 是因为可能存在多条数据
    await this.prismaService.friendRequest.updateMany({
      where: {
        fromUserId: fromId,
        toUserId: userId,
        status: 'Pending',
      },
      data: {
        status: 'Approved',
      },
    });

    // 先看该关系是否已存在，不存在则插入
    const isExistRelation = await this.prismaService.friendShip.findMany({
      where: {
        userId,
        friendId: fromId,
      },
    });

    // 往好友列表中插入数据
    if (!isExistRelation.length) {
      await this.prismaService.friendShip.create({
        data: {
          userId,
          friendId: fromId,
        },
      });
    }

    return '已同意';
  }

  // 拒绝申请接口
  async reject(userId: number, friendId: number) {
    // 更新好友请求状态->已拒绝，用 updateMany 是因为可能存在多条数据
    await this.prismaService.friendRequest.updateMany({
      where: {
        fromUserId: friendId,
        toUserId: userId,
        status: 'Pending',
      },
      data: {
        status: 'Rejected',
      },
    });

    return '已拒绝';
  }

  // 获取好友列表
  async getFriendship(userId: number, name: string) {
    // 对方是我的好友、我是对方的好友，都算作互相是好友。 [{userId: 1, friendId: 2}, {userId: 2, friendId: 1}]
    const friends = await this.prismaService.friendShip.findMany({
      where: {
        OR: [{ userId }, { friendId: userId }],
      },
    });

    // 去重：1 和 2 ， 2 和 1 算作一条数据
    const set = new Set<number>();
    for (let i = 0; i < friends.length; i++) {
      set.add(friends[i].userId);
      set.add(friends[i].friendId);
    }

    // 过滤掉自身
    const friendIds = Array.from(set).filter((id) => id !== userId);

    let result = [];
    // 根据ID查询用户信息
    for (let i = 0; i < friendIds.length; i++) {
      const firend = await this.prismaService.user.findUnique({
        where: {
          id: friendIds[i],
        },
        select: {
          id: true,
          username: true,
          nickName: true,
          avatar: true,
          email: true,
        },
      });
      result.push(firend);
    }

    return result.filter((item) => item.nickName.includes(name));
  }

  // 删除好友接口
  async remove(userId: number, friendId: number) {
    await this.prismaService.friendShip.deleteMany({
      where: {
        userId,
        friendId,
      },
    });
    return '删除成功';
  }
}
